<template>
  <div class="systemRoute">
    <div class="filter-container">
      <el-cascader
        v-model="listQuery.search.system_id"
        placeholder="选择菜单或者系统"
        clearable
        :options="queryOptions"
        :show-all-levels="false"
        style="width: 220px"
        class="filter-item"
        @change="getList"
        key="table"
      >
      </el-cascader>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        查询
      </el-button>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="handleCreate"
      >
        新增
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      stripe
      fit
      row-key="id"
      highlight-current-row
      style="width: 100%;margin-bottom: 20px;"
      :tree-props="{ children: 'children' }"
    >
      <el-table-column label="所属系统" min-width="250px" align="left">
        <template slot-scope="scope">
          <el-tag
            style="cursor: pointer;"
            :type="scope.row.system_id ? 'success' : 'primary'"
            effect="dark"
          >
            <template v-if="scope.row.system_id">
              <span @click="handleSystemDetail(scope.row.system_id)">{{
                'http请求：' + scope.row.system.name || ''
              }}</span>
            </template>
            <template v-else>
              <span>菜单</span>
            </template>
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="备注" min-width="120px" align="left">
        <template slot-scope="scope">
          <span>{{ scope.row.remark || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="系统ID" width="80px" align="right">
        <template slot-scope="scope">
          <span v-if="!scope.row.fatherRoute">{{ scope.row.system_id }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="路径ID" width="80px" align="right">
        <template slot-scope="scope">
          <span v-if="!scope.row.fatherRoute">{{ scope.row.id }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column label="路径名" width="180px" align="left">
        <template slot-scope="scope">
          <span v-if="!scope.row.fatherRoute">{{ scope.row.name }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" width="160px" align="left">
        <template slot-scope="scope">
          <span v-if="!scope.row.fatherRoute">{{ scope.row.create_by }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        :min-width="settings['tableWidth']['timeYMS']"
        align="left"
      >
        <template slot-scope="scope">
          <span v-if="!scope.row.fatherRoute">{{
            scope.row.create_at | parseTime
          }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="180">
        <template slot-scope="{ row }" v-if="!row.fatherRoute">
          <el-tooltip
            class="item"
            effect="dark"
            content="编辑"
            placement="bottom"
          >
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              circle
              @click="handleUpdate(row)"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip
            class="item"
            effect="dark"
            content="删除"
            placement="bottom"
          >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              circle
              @click="handleDelete(row)"
            >
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="listQuery.page.current"
      :page-sizes="[10, 20, 50]"
      :page-size="listQuery.page.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination> -->
    <!-- 弹窗配置 -->
    <el-dialog
      :modal-append-to-body="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      width="600px"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model.sync="tempData"
        label-position="right"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="菜单/系统" prop="system_id">
          <el-cascader
            v-model="tempData.system_id"
            placeholder="选择菜单或者系统"
            clearable
            :options="queryOptions"
            :show-all-levels="false"
            @change="handleDialogElCascader"
            key="dialog"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="路径名" prop="name">
          <el-input
            v-model="tempData.name"
            placeholder="路径名：如/system/user"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2 }"
            maxlength="100"
            minRows="2"
            show-word-limit
            v-model="tempData.remark"
            placeholder="请填写备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ '取消' }}
        </el-button>
        <el-button
          type="primary"
          :loading="confirmButtonLoading"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
// 具体用法查看官方API:https://github.com/kaorun343/vue-property-decorator
import { Component, Vue, Watch, Prop } from 'vue-property-decorator'
import { MessageBox } from 'element-ui'
import {
  systemGetRouteList,
  systemCreateRoute,
  systemModifyRoute,
  systemDeleteRoute
} from '@/api/system/route'

import { systemGetSystemList } from '@/api/system/system'
import { parseTimeJS as parseTime } from '@/utils'
import { Form } from 'element-ui'
import { cloneDeep } from 'lodash'
import { isValidMobile, isValidEmail } from '@/utils/validate'
interface IUserData {
  id?: number | string
  system_id: number | undefined | any[]
  name: string
  remark: string
}
const defaultData: IUserData = {
  system_id: undefined,
  name: '',
  remark: ''
}
@Component({
  name: 'systemRoute',
  components: {
    //引用的组件在这里声明
  }
})
export default class extends Vue {
  private tempData = cloneDeep(defaultData)
  private validateName = (rule: any, value: string, callback: Function) => {
    if (value.length < 1) {
      callback(new Error('请输入用户名'))
    } else {
      callback()
    }
  }
  @Prop({ default: '' }) private propExp1!: string
  // @Prop({ required: true }) private propExp2?: boolean
  private dataExp: any = ''
  private queryOptions: any[] = [
    {
      value: 0,
      label: '菜单',
      children: [{ value: 0, label: '所有菜单' }]
    },
    { value: 1, label: '系统-http请求', children: [] }
  ]
  // 弹窗配置
  private dialogStatus = ''
  private dialogFormVisible = false
  private textMap = {
    update: '编辑',
    create: '新增'
  }
  private rules = {
    name: [{ required: true, message: '请填写路径名', trigger: 'blur' }],
    system_id: [{ required: true, message: '请选择系统', trigger: 'change' }]
  }
  private confirmButtonLoading = false
  get computedExp() {
    //computed 属性
    return true
  }
  created() {
    // 最早可以调用vue组件method的钩子
    this.getSystemList()
  }
  mounted() {
    //mounted 钩子
    this.getList()
  }
  // 表loading状态
  private listLoading: boolean = false
  private list: any[] = []
  private total = 0
  // 公共查询对象
  private listQuery = {
    search: {
      // 级联选择器是个数组
      system_id: []
    },
    orderby: {
      field: undefined,
      direction: undefined
    }
  }
  // 跳转页码查询
  handleCurrentChange(val: any) {
    this.getList()
  }
  // size切换查询
  private handleSizeChange(val: any) {
    this.getList()
  }
  // 处理属于同一个子系统路或者菜单路径
  private executeData(list: any[]) {
    let tempList = list.reduce((item: any, next: any) => {
      let temIndex = item.findIndex((it: any) => {
        return it.system_id === next.system_id
      })
      if (temIndex >= 0) {
        item[temIndex].children.push(next)
      } else {
        item.push({
          id: next.id + '父级',
          system_id: next.system_id,
          system: {
            name: next.system ? next.system.name : '菜单路径'
          },
          fatherRoute: true,
          remark: next.system_id
            ? `这是${next.system.name}系统-http请求配置`
            : '这是所有菜单路径',
          children: [{ ...next }]
        })
      }
      return item
    }, [])
    tempList.sort((a: any, b: any) => {
      return a.system_id - b.system_id
    })
    return tempList
  }
  private async getList() {
    this.listLoading = true
    // ajax 请求相应list
    const { data } = await systemGetRouteList({
      search: {
        system_id: cloneDeep(this.listQuery.search.system_id).pop()
      },
      orderby: this.listQuery.orderby
    })
    this.list = this.executeData(cloneDeep(data.list))
    this.listLoading = false
  }
  private handleFilter() {
    this.getList()
  }
  //下载
  private handleDownload() {}
  // 新增
  private handleCreate() {
    this.resetData()
    this.dialogStatus = 'create'
    this.dialogFormVisible = true
    this.$nextTick(() => {
      ;(this.$refs['dataForm'] as Form).clearValidate()
    })
  }
  private resetData() {
    this.tempData = cloneDeep(defaultData)
  }
  // 新增
  private createData() {
    ;(this.$refs['dataForm'] as Form).validate(async valid => {
      if (valid) {
        this.confirmButtonLoading = true
        let cloneData = cloneDeep(this.tempData)
        cloneData.system_id = (cloneData.system_id as any[]).pop()
        try {
          const { data } = await systemCreateRoute(Object.assign(cloneData))
        } catch (error) {
          console.error(error)
        } finally {
          this.confirmButtonLoading = false
        }
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '创建成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      }
    })
  }
  // 打开弹窗编辑
  private async handleUpdate(row: any) {
    this.tempData = cloneDeep(row)
    this.tempData.system_id = this.tempData.system_id
      ? [1, this.tempData.system_id as number]
      : [0, 0]
    this.dialogStatus = 'update'
    this.dialogFormVisible = true
    this.$nextTick(() => {
      ;(this.$refs['dataForm'] as Form).clearValidate()
    })
  }
  // 更新
  private updateData() {
    ;(this.$refs['dataForm'] as Form).validate(async valid => {
      if (valid) {
        let cloneData = cloneDeep(this.tempData)
        cloneData.system_id = (cloneData.system_id as any[]).pop()
        let tempPostData = {
          id: parseInt(cloneData.id as string),
          system_id: cloneData.system_id,
          name: cloneData.name,
          remark: cloneData.remark
        }
        this.confirmButtonLoading = true
        try {
          const { data } = await systemModifyRoute(tempPostData)
        } catch (error) {
          console.error(error)
        } finally {
          this.confirmButtonLoading = false
        }
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      }
    })
  }
  private cancelEdit(row: any) {
    row.title = row.originalStatus
    this.$message({
      message: 'The title has been restored to the original value',
      type: 'warning'
    })
  }
  // 删除操作
  private async handleDelete(row: any) {
    this.tempData = cloneDeep(row)
    MessageBox.confirm(`确定删除 '${row.name}' 路径？`, '确定', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const { data } = await systemDeleteRoute({ id: this.tempData.id })
      this.dialogFormVisible = false
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.getList()
    })
  }

  private async getSystemList() {
    // ajax 请求相应list

    this.queryOptions[1].children = []
    const { data } = await systemGetSystemList()
    data.list.forEach((item: any) => {
      this.queryOptions[1].children.push({
        value: item.id,
        label: item.name
      })
    })
  }
  // 查看子系统详情
  private handleSystemDetail(id: string) {
    this.$router.push({
      path: '/system/system/detail?id=' + id
    })
  }
  private handleDialogElCascader() {
    console.log(arguments)
  }
}
</script>

<style lang="scss" scoped>
.systemRoute {
  padding: 20px;
}
.el-select,
.el-cascader {
  width: 100%;
}
</style>
